/*
 * @Author: lihaogn
 * @Date: 2022-01-21 11:29:49
 * @LastEditTime: 2022-01-26 15:39:15
 * @LastEditor: lihaogn
 * @Description: 文件上传
 * @FilePath: \lix-admin-server\app\controller\upload.js
 */
const Controller = require("egg").Controller;
const fs = require("fs");
const { SuccessResponse, ErrorResponse } = require("../dto/responseDto");

class UploadController extends Controller {
  /**
   * @author: lihaogn
   * @Date: 2022-01-26 15:27:54
   * @description: 下载文件
   * @param {*}
   * @return {*}
   */
  async download() {
    const { ctx } = this;

    const res = await ctx.service.upload.download(ctx.query.id);

    if (res === false) {
      ctx.body = new ErrorResponse(null, "下载失败");
    } else {
      ctx.attachment(res.name);
      ctx.set("Content-Type", "application/octet-stream");
      ctx.body = fs.createReadStream(res.path);
    }
  }
  /**
   * @author: lihaogn
   * @Date: 2022-01-24 20:58:57
   * @description: 删除文件
   * @param {*}
   * @return {*}
   */
  async deleteUpload() {
    const { ctx } = this;

    const res = await ctx.service.upload.deleteUpload(ctx.query.id);
    if (res === false) {
      ctx.body = new ErrorResponse(null, "删除失败");
    } else {
      ctx.body = new SuccessResponse(null, "删除成功");
    }
  }
  /**
   * @author: lihaogn
   * @Date: 2022-01-23 21:45:18
   * @description: 获取上传文件列表
   * @param {*}
   * @return {*}
   */
  async getList() {
    const { ctx } = this;

    const res = await ctx.service.upload.queryUploads();

    if (res === false) {
      ctx.body = new ErrorResponse(null, "查询上传文件列表失败");
    } else {
      ctx.body = new SuccessResponse(res, "");
    }
  }
  /**
   * @author: lihaogn
   * @Date: 2022-01-23 14:50:26
   * @description: 处理小文件上传（<50M)
   * @param {*}
   * @return {*}
   */
  async upload() {
    const { ctx } = this;

    const file = ctx.request.files[0];
    let fileName = file.filename;
    let message = "";
    const path = "/public/upload/" + fileName;
    const dest = "app" + path;

    let result = await new Promise((resolve, reject) => {
      fs.copyFile(file.filepath, dest, (error) => {
        if (error) {
          message += fileName + "上传失败；";
          reject(error);
        } else {
          resolve(true);
        }
      });
    });

    // 清除上传的临时文件
    ctx.cleanupRequestFiles();

    if (result) {
      // 信息入库
      const res = await ctx.service.upload.createUpload(
        dest,
        fileName,
        "http://localhost:7001" + path
      );
      if (res === false) {
        ctx.body = new ErrorResponse(result, message);
      } else {
        ctx.body = new SuccessResponse(
          { id: res.id, url: res.url },
          "上传成功"
        );
      }
    } else {
      ctx.body = new ErrorResponse(result, message);
    }
  }
}

module.exports = UploadController;
